package cn.com.xj.plat.controller;

import cn.com.xj.common.param.out.ServiceResp;
import cn.com.xj.common.param.valid.ValidUtils;
import cn.com.xj.common.service.aspect.md5.Md5Util;
import cn.com.xj.plat.evt.LoginEvt;
import cn.com.xj.plat.model.SessionLoginUser;
import cn.com.xj.plat.service.LoginService;
import cn.com.xj.plat.util.LoginUtils;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 *
 */
@Controller
@EnableAutoConfiguration
@RequestMapping("/login")
public class LoginController{
	
	private static final Logger log = LoggerFactory.getLogger(LoginController.class);

    private static String IMG_CODE_KEY = "veryCode";
    private static String IMG_CODE_SESSION_KEY = "img_session_code";

    @Autowired
    private LoginService loginService;

    @RequestMapping("/index")
    public String index() {
        return "login";
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        LoginUtils.removeLogUser(session);
        return "login";
    }
    /**
     * 登录
     */
    @RequestMapping(value = "/doLogin",method = RequestMethod.POST)
    @ResponseBody
    public ServiceResp doLogin(LoginEvt evt, HttpServletRequest request,
                               HttpServletResponse response, HttpSession session) {
        ServiceResp resp = new ServiceResp();
        try {
            ServiceResp validResp = new ValidUtils().validate(evt);
            if(!validResp.success()) {
                return validResp.error(validResp.getHead().getRespMsg());
            }
            Map<String, Object> returnMap = checkRandCode(request);
            if((Integer)returnMap.get("retCode")!=0){
                return resp.error((String)returnMap.get("retMsg"));
            }
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("loginName", evt.getLoginName());//登录账号
            param.put("loginPassword", Md5Util.MD5(evt.getLoginPassword()));//登录密码
            resp = loginService.login(param);
            if(resp.success()){
                String val = JSON.toJSONString(resp.getBody());
                SessionLoginUser sessionLoginUser = JSON.parseObject(val,SessionLoginUser.class);
                HttpSession httpSession = request.getSession();
                httpSession.setAttribute(LoginUtils.USER_SESSION_KEY,sessionLoginUser);
            }
            return resp;
        } catch (Exception e) {
        	log.error(e.getMessage(), e);
            return resp.error("系统异常,请稍后再试");
        }
    }

    public Map<String, Object> checkRandCode(HttpServletRequest request) {
        HashMap returnMap = new HashMap();
        String imgCodeKey = request.getParameter("imgCodeKey");
        if(StringUtils.isBlank(imgCodeKey)) {
            imgCodeKey = IMG_CODE_KEY;
        }

        String imgCodeSessionKey = request.getParameter("imgCodeSessionKey");
        if(StringUtils.isBlank(imgCodeSessionKey)) {
            imgCodeSessionKey = IMG_CODE_SESSION_KEY;
        }
        String veryCode = request.getParameter(imgCodeKey);
        if(StringUtils.isBlank(veryCode)) {
            returnMap.put("retCode", Integer.valueOf(-1));
            returnMap.put("retMsg", "图片验证码为空");
            return returnMap;
        } else {
            String validateC = (String)request.getSession().getAttribute(imgCodeSessionKey);
            if(StringUtils.isBlank(validateC)) {
                returnMap.put("retCode", Integer.valueOf(-1));
                returnMap.put("retMsg", "请获取图片验证码");
                return returnMap;
            } else {
                String validateCL = validateC.toLowerCase();
                String veryCodeL = veryCode.toLowerCase();
                if(!validateCL.equals(veryCodeL)) {
                    returnMap.put("retCode", Integer.valueOf(-1));
                    returnMap.put("retMsg", "图片验证码错误");
                    return returnMap;
                } else {
                    request.getSession().removeAttribute(imgCodeSessionKey);
                    returnMap.put("retCode", Integer.valueOf(0));
                    returnMap.put("retMsg", "图片验证码正确");
                    return returnMap;
                }
            }
        }
    }

}
